import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import permission from './modules/permission'
import theme from './modules/theme'
import getters from './getters'

Vue.use(Vuex)

// 确保存储路由对象的完整信息
const saveViewToStorage = (views) => {
  // 存储之前确保对象可以被序列化
  const serializedViews = views.map(view => ({
    name: view.name,
    path: view.path,
    fullPath: view.fullPath || view.path,
    meta: view.meta || {},
    title: view.meta?.title || view.title || 'no-name',
    params: view.params || {}
  }))
  
  localStorage.setItem('visitedViews', JSON.stringify(serializedViews))
}

// 定义tagsView模块
const tagsView = {
  namespaced: true,
  state: {
    visitedViews: JSON.parse(localStorage.getItem('visitedViews') || '[]'),
    cachedViews: []
  },
  mutations: {
    ADD_VISITED_VIEW: (state, view) => {
      if (state.visitedViews.some(v => v.path === view.path)) {
        // 如果已存在，则更新
        state.visitedViews = state.visitedViews.map(v => {
          if (v.path === view.path) {
            return Object.assign({}, v, {
              title: view.meta?.title || 'no-name',
              meta: view.meta || {}
            })
          }
          return v
        })
      } else {
        // 如果不存在，则添加
        state.visitedViews.push(
          Object.assign({}, view, {
            title: view.meta?.title || 'no-name'
          })
        )
      }
      
      // 保存到localStorage
      saveViewToStorage(state.visitedViews)
    },
    ADD_CACHED_VIEW: (state, view) => {
      if (state.cachedViews.includes(view.name)) return
      if (!view.meta?.noCache) {
        state.cachedViews.push(view.name)
      }
    },
    DEL_VISITED_VIEW: (state, view) => {
      for (const [i, v] of state.visitedViews.entries()) {
        if (v.path === view.path) {
          state.visitedViews.splice(i, 1)
          break
        }
      }
      // 更新localStorage
      saveViewToStorage(state.visitedViews)
    },
    DEL_CACHED_VIEW: (state, view) => {
      const index = state.cachedViews.indexOf(view.name)
      index > -1 && state.cachedViews.splice(index, 1)
    },
    DEL_ALL_VISITED_VIEWS: state => {
      // 保留固定的标签页
      const affixTags = state.visitedViews.filter(tag => tag.meta?.affix)
      state.visitedViews = affixTags
      // 更新localStorage
      saveViewToStorage(state.visitedViews)
    },
    DEL_ALL_CACHED_VIEWS: state => {
      state.cachedViews = []
    },
    UPDATE_VISITED_VIEW: (state, view) => {
      for (let i = 0; i < state.visitedViews.length; i++) {
        if (state.visitedViews[i].path === view.path) {
          state.visitedViews[i] = Object.assign({}, state.visitedViews[i], view)
          break
        }
      }
      // 更新localStorage
      saveViewToStorage(state.visitedViews)
    }
  },
  actions: {
    addView({ dispatch }, view) {
      dispatch('addVisitedView', view)
      dispatch('addCachedView', view)
    },
    addVisitedView({ commit }, view) {
      commit('ADD_VISITED_VIEW', view)
    },
    addCachedView({ commit }, view) {
      commit('ADD_CACHED_VIEW', view)
    },
    delView({ dispatch, state }, view) {
      return new Promise(resolve => {
        dispatch('delVisitedView', view)
        dispatch('delCachedView', view)
        resolve({
          visitedViews: [...state.visitedViews],
          cachedViews: [...state.cachedViews]
        })
      })
    },
    delVisitedView({ commit, state }, view) {
      return new Promise(resolve => {
        commit('DEL_VISITED_VIEW', view)
        resolve([...state.visitedViews])
      })
    },
    delCachedView({ commit, state }, view) {
      return new Promise(resolve => {
        commit('DEL_CACHED_VIEW', view)
        resolve([...state.cachedViews])
      })
    },
    delAllViews({ dispatch, state }) {
      return new Promise(resolve => {
        dispatch('delAllVisitedViews')
        dispatch('delAllCachedViews')
        resolve({
          visitedViews: [...state.visitedViews],
          cachedViews: [...state.cachedViews]
        })
      })
    },
    delAllVisitedViews({ commit, state }) {
      return new Promise(resolve => {
        commit('DEL_ALL_VISITED_VIEWS')
        resolve([...state.visitedViews])
      })
    },
    delAllCachedViews({ commit, state }) {
      return new Promise(resolve => {
        commit('DEL_ALL_CACHED_VIEWS')
        resolve([...state.cachedViews])
      })
    },
    updateVisitedView({ commit }, view) {
      commit('UPDATE_VISITED_VIEW', view)
    }
  }
}

// 定义app模块
const app = {
  namespaced: true,
  state: {
    loading: false,
    cancelTokens: [] // 存储请求取消标识
  },
  mutations: {
    SET_LOADING: (state, status) => {
      state.loading = status
    },
    addCancelToken: (state, { url, cancel }) => {
      state.cancelTokens.push({ url, cancel })
    },
    removeCancelToken: (state, url) => {
      state.cancelTokens = state.cancelTokens.filter(item => item.url !== url)
    },
    clearCancelTokens: (state) => {
      state.cancelTokens = []
    }
  },
  actions: {
    // 取消所有请求
    cancelAllRequests({ state, commit }) {
      state.cancelTokens.forEach(item => {
        item.cancel('操作取消')
      })
      commit('clearCancelTokens')
    }
  }
}

export default new Vuex.Store({
  modules: {
    app,
    user,
    permission,
    tagsView,
    theme
  },
  getters
}) 